import React from 'react';
import {connect} from 'dva';
import queryString from 'query-string';
import { getMastId, getMastKey } from '@/utils/tools';
import { Accordion, List, NavBar, Icon, Toast, Modal } from 'antd-mobile';
import styles from './index.less';
import { requestSuccess, removeHidden } from '@/utils/tools';
import UserServices from '@/services/user';
import { apiMaps } from '@/utils/maps';
import Constants from '@/utils/constants';
import SeModal from '@/components/searchEmployee';
const prompt = Modal.prompt;

class DetailPage extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      simpleModal: false,
      simpleModalTitle: '',
      simpleModalCallback: ''
    }

  }

  componentDidMount() {

  }

  componentWillUnmount(){
    // SeModal.close();
  }

  handleToggle = (key) => {
    this.setState({activeKeys: key})
  }

  handleCloseSimpleModal = () => {
    this.props.history.push(`/`);
  }

  handleClickFootBtn = (btn) => {
    const id = getMastId();
    const requestKey = getMastKey();
    const query = queryString.parse(this.props.location.search);

    const mast = this.props.detail.mast;

    const submitSuccess = (res) => {
      if(requestSuccess(res)){
        if(btn.name == 'Posting to SAP' || btn.name.toLowerCase().indexOf('ticket') !== -1){
          this.setState({
            simpleModal: true,
            simpleModalTitle: res.data.successMessage || 'success'
          })
        }else{
          Toast.success('Submit Success');
          this.props.history.push(`/`);
        }
      }else{
        submbitError(new Error(res.data && res.data.errorMessage || new Error('error')));
      }
    }

    const submbitError = (e) => {
      if(e){
        const message = e.message || 'Error';
        Toast.fail(message);
      }
    }
    if(btn.id == 'saveDraft'){
      UserServices.saveDraftDetail({
        ...id,
        trsMast: {
          cities: mast.cities,
          dptrDay: global.moment(mast.dptrDay).format('YYYY-MM-DD'),
          expDptrDayStatus: mast.expDptrDayStatus,
          rtnDay: global.moment(mast.rtnDay).format('YYYY-MM-DD'),
          expRtnDayStatus: mast.expRtnDayStatus,
          requestorRemarks: mast.requestorRemarks,
          needAdvance: mast.needAdvance?'YES':'NO',
          needReimbursement: mast.needReimbursement?'YES':'NO',
          subCompanys: mast.subCompanys,
          type: mast.type,
          purpose: mast.purpose
        }
      }).then(submitSuccess).then(submbitError)
    }else if (btn.id == 'submit'){
      UserServices.submitDetail({
        ...id,
        trsMast: {
          cities: mast.cities,
          dptrDay: global.moment(mast.dptrDay).format('YYYY-MM-DD'),
          expDptrDayStatus: mast.expDptrDayStatus,
          rtnDay: global.moment(mast.rtnDay).format('YYYY-MM-DD'),
          expRtnDayStatus: mast.expRtnDayStatus,
          requestorRemarks: mast.requestorRemarks,
          needAdvance: mast.needAdvance?'YES':'NO',
          needReimbursement: mast.needReimbursement?'YES':'NO',
          subCompanys: mast.subCompanys,
          type: mast.type,
          purpose: mast.purpose
        }
      }).then(submitSuccess).then(submbitError)
    }else if (btn.name == 'Consult'){
      SeModal.open({
        defaultKeyword: mast.applicant,
        success: (result) => {
          console.log(result);
          if(result && !result.employees){
            Toast.fail('Please select employees');
            return;
          }
          // consult 按钮提交
          UserServices.saveDetailOfParams({
             ...id,
             actionId: btn.id,
             actionName: btn.name,
             [requestKey]: {
               consultOwner: result.employees
             },
             remark: mast.remark,
             actionType: query.actionType //actionType不提交到后台
           }).then(submitSuccess).then(submbitError)
        },
        cancel: () => {

        }
      })
    }else{
      const hasActualTravelDetails = this.props.showComponents.find(zz => zz.key == 'ActualTravelDetails');
      if(btn.name !== 'Cancel' && (hasActualTravelDetails && hasActualTravelDetails.edit)){
        const needCompare = ['citiesChange', 'dptrDayChange', 'expDptrDayStatusChange', 'rtnDayChange', 'expRtnDayStatusChange', 'typeChange', 'purposeChange'];
        let targetLabels = global._.filter(needCompare, item => {
          const orginItem = item.replace('Change', '');
          let orgin = this.props.detail.copyActualDetail[orginItem];
          let current = mast[item];
          if((item == 'dptrDayChange' || item == 'rtnDayChange')){
            current = global.moment(mast[item]).valueOf() || '';
          }
          console.log(`orgin: ${orgin}`);
          console.log(`current: ${current}`);
          if(current && (current + '').length > 0 && !global._.isEqual(orgin, current) && !mast[item.replace('Change', 'Reason')]){
            return true;
          }
        });
        if(targetLabels && targetLabels.length > 0){
          Toast.fail(`You mast input reason when ${targetLabels[0]} changed`);
          return;
        }
      }
      const getParams = (key) => {
        if(key == 'trsMast'){
          const data = global._.pick(mast, ['sapDocNo', 'citiesChange', 'citiesReason', 'dptrDayChange', 'dptrDayReason', 'expDptrDayStatusChange', 'expDptrDayStatusReason', 'rtnDayChange', 'rtnDayReason', 'expRtnDayStatusChange', 'expRtnDayStatusReason','purposeChange', 'purposeReason', 'needReimbursement', 'payee', 'accountHolder', 'bankAccount', 'bankName']);
          return {
            ...data,
            subCompanysReason: mast.typeReason || '', //与type合并
            needReimbursement: mast.needReimbursement?'YES':'NO',
            dptrDayChange: mast.dptrDayChange && global.moment(mast.dptrDayChange).format('YYYY-MM-DD') || '',
            rtnDayChange: mast.rtnDayChange && global.moment(mast.rtnDayChange).format('YYYY-MM-DD') || ''
          }
        }else if(key == 'advMast'){
          return {};
        }else{
          return {};
        }
      }
      UserServices.saveDetailOfParams({
        ...id,
        actionId: btn.id,
        actionName: btn.name,
        [requestKey]: getParams(requestKey),
        remark: mast.remark,
        actionType: query.actionType //actionType不提交到后台
      }).then(submitSuccess).then(submbitError)
    }

  }

  render(){
    return (
      <div className={styles.detail}>
        <Modal
         visible={this.state.simpleModal}
         transparent
         maskClosable={false}
         title={this.state.simpleModalTitle}
         footer={[{ text: 'Ok', onPress: () => { this.handleCloseSimpleModal('simpleModal') } }]}
         wrapProps={{ onTouchStart: this.onWrapTouchStart }}
       >
       </Modal>
        {
          !Constants.hasCordova
          ?
        <NavBar
          mode='dark'
          icon={< Icon type = 'left' />}
          onLeftClick={() => console.log('onLeftClick')}
          rightContent={[< Icon key = '1' type = 'ellipsis' />]}>
          Travel Request System
        </NavBar>
        :
        null
      }
        {/*
          <Accordion activeKey={global._.map(this.props.showComponents, item => item.key)} className='my-accordion' onChange={this.handleToggle}>
          {
          this.props.showComponents.map(item => {
          const Path = item.path;
          return (
          <Accordion.Panel header={item.title} key={item.key}>
          <Path history={this.props.history} edit={item.edit} extraEditArr={item.extraEditArr} />
          </Accordion.Panel>
          )
          })
          }
          </Accordion>
        */}
        <div className={styles.results}>
          <div className={styles.wrapper}>
            {
              this.props.showComponents.map(item => {
                const Path = item.path;
                return (
                  <div className={styles.panel} key={item.key}>
                    <div className={styles.panelTitle}>{item.title}</div>
                    <div>
                      <Path history={this.props.history} edit={item.edit} extraEditArr={item.extraEditArr} />
                    </div>
                  </div>
                )
              })
            }
          </div>
        </div>
        {
          this.props.detail.mast.status == 'cTrip Process'
          ?
          <div className={styles.warningInfo}>
            *若使用携程商旅预订火车票需取票乘车并保留火车票 Train ticket needs to be kept when you book with Ctrip
          </div>
          :
          ''
        }
        {
          this.props.detail.mobileAvailableActions && this.props.detail.mobileAvailableActions.length>0 ?

          <div className={styles.footerBtns} onClick={this.handleGoNewApplication}>
            {
              this.props.detail.mobileAvailableActions.map(item => {
                return (
                  <div key={item.id} onClick={() => this.handleClickFootBtn(item)}>{item.name}</div>
                )
              })
            }
          </div>
          :
          null
        }
      </div>
    )
  }
}


DetailPage.propTypes = {};

function mapStateToProps(state) {
  return {
    ...state.detail
  }
}
export default connect(mapStateToProps)(DetailPage);
